/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-07-31 09:10:41
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-08-21 15:21:00
 * @FilePath: /vue3-uniapp/src/components/ui/MescrollView/useNetwork.ts
 */
import { useNotifySubject } from '@/service/app/useNotifySubject';

import { useBeforeRouteLeave } from '@/service/hook/useBeforeRouteLeave';
import { onShow } from '@dcloudio/uni-app';

export const useNetwork = () => {
    const { success, danger } = useNotifySubject();

    const isIOS = uni.getSystemInfoSync().platform === 'ios';
    const isConnected = ref(true);
    const networkType = ref('');
    const handleNetworkStatusChange = (
        res: UniNamespace.OnNetworkStatusChangeSuccess
    ) => {
        isConnected.value = res.isConnected;
        networkType.value = res.networkType;
        // danger({
        //     msg: `${isConnected.value} ${networkType.value}`
        // });
    };

    uni.getNetworkType({
        success: (res) => {
            networkType.value = res.networkType;
            if (res.networkType === 'none') {
                isConnected.value = false;
            } else {
                isConnected.value = true;
            }
        }
    });

    const getNetworkType = () => {
        uni.getNetworkType({
            success: (res) => {
                networkType.value = res.networkType;
                if (res.networkType == 'none') {
                    danger({
                        msg: '无网络连接'
                    });
                    isConnected.value = false;
                } else {
                    success({
                        msg: '网络已连接'
                    });
                    isConnected.value = true;
                }
            }
        });
    };

    onShow(() => {
        uni.onNetworkStatusChange(handleNetworkStatusChange);
    });
    useBeforeRouteLeave(() => {
        uni.offNetworkStatusChange(handleNetworkStatusChange);
    });

    return {
        isIOS,
        isConnected,
        networkType,
        getNetworkType
    };
};
